package com.xinchao.job.task;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xinchao.common.constant.CmccApiConstant;
import com.xinchao.common.constant.DateFormatConstant;
import com.xinchao.common.dto.CityCmccInfoDTO;
import com.xinchao.common.dto.DeviceSimInfoActivationTimeDTO;
import com.xinchao.common.util.CmccApiUtils;
import com.xinchao.common.util.DateUtils;
import com.xinchao.common.util.ListUtil;
import com.xinchao.job.service.CityCmccInfoService;
import com.xinchao.job.service.DeviceSimInfoService;

/**
 * 更新终端sim卡信息激活时间、号码（mssidn）；在获取激活时间是，也把sim卡的mssidn信息一起查询出来，在中国移动数据库里，iccid与mssidn是绑定的
 *
 * @author dxy
 * @date 2018/9/10 16:56
 */
@DisallowConcurrentExecution
public class SimActivationTimeJob extends QuartzJobBean {
	private static Logger logger = LoggerFactory.getLogger(SimActivationTimeJob.class);
	@Autowired
	private DeviceSimInfoService deviceSimInfoService;
	@Autowired
	private CityCmccInfoService cityCmccInfoService;

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		//4.1.1.1.9	批量号码激活时间查询
		String method = "triopi.member.actitime.batch.query";
		try {
			//城市对应的集团编码，应用键对应值，密钥的MAP
			Map<String, CityCmccInfoDTO> cityCmccInfoMap = cityCmccInfoService.getCityCmccInfoMap();
			if (cityCmccInfoMap != null && cityCmccInfoMap.size() > 0) {
				Set<String> citySet = cityCmccInfoMap.keySet();
				for (String city : citySet) {
					//获取城市对应的集团编码，应用键对应值，密钥
					CityCmccInfoDTO cityCmccInfoDTO = cityCmccInfoMap.get(city);
					//应用键,由中国移动提供
					String appKeyValue = cityCmccInfoDTO.getAppKey();
					//加密密钥，由中国移动提供
					String secrect = cityCmccInfoDTO.getSecrect();
					//10位集团编码，由中国移动提供
					String groupCode = cityCmccInfoDTO.getGroupCode();
//					logger.info("updateDeviceSimInfoActivationTime_start_time:" + DateUtils.longTimeStampToStringDate(System.currentTimeMillis(), DateFormatConstant.LONG_DATE_FORMAT_STR_CH));
					//获取终端sim卡没有激活时间总数
					Long count = deviceSimInfoService.countDeviceSimInfoNoActivationTime(city);
					if (count > 0) {
						List<DeviceSimInfoActivationTimeDTO> activationTimeList = deviceSimInfoService.listDeviceSimInfoActivationTime(city);
						if (CollectionUtils.isNotEmpty(activationTimeList)) {
							// 移动接口单次仅支持100条数据查询
							List<List<DeviceSimInfoActivationTimeDTO>> singleLimitAssign = ListUtil.singleLimitAssign(activationTimeList, 100);
							for ( int j = 0; j < singleLimitAssign.size(); j++ ) {
								// 将iccid拼接整字符串，用逗号隔开
								StringBuilder sb = new StringBuilder();
								for ( DeviceSimInfoActivationTimeDTO device : singleLimitAssign.get(j) ) {
									sb.append(device.getIccid()).append(",");
								}
								String iccids = sb.toString();
								iccids = iccids.substring(0,iccids.length()-1);
//								logger.info("updateDeviceSimInfoActivationTime_iccids: " + iccids);
								//将iccidSb的长度清零，重复使用
								sb.setLength(0);
								//调用移动接口，获取sim卡激活时间、mssidn
								String data = CmccApiUtils.bachQuery(method, iccids, true, "", appKeyValue, secrect, groupCode);
								// 解析返回报文，批量更新
								bathSetActivationTime(data);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceSimInfoSchedule updateDeviceSimInfoActivationTime 更新终端sim卡信息激活时间失败：" + e.getMessage());
		}
	}
	
	private void bathSetActivationTime(String data) {
//		logger.info(">> updateDeviceSimInfoActivationTime_data CmccApiUtils.bachQuery: " + data);
		// 转化为JSONObject
		JSONObject dataJsonObj = JSON.parseObject(data);
		// 获取msisdnList
		JSONObject msisdnJsonObj = dataJsonObj.getJSONObject(CmccApiConstant.JSON_KEY_MSISDN_LIST);
		if (msisdnJsonObj != null) {
			JSONArray jsonArray = msisdnJsonObj.getJSONArray(CmccApiConstant.JSON_KEY_LIST);
			if (jsonArray != null && jsonArray.size() > 0) {
				List<DeviceSimInfoActivationTimeDTO> list = new ArrayList<>();
				for (int j = 0; j < jsonArray.size(); j++) {
					JSONObject jsonObject = jsonArray.getJSONObject(j);
					String activationTime = jsonObject.getString(CmccApiConstant.JSON_KEY_TIME);
					String msisdn = jsonObject.getString(CmccApiConstant.JSON_KEY_MSISDN);
					String iccid = jsonObject.getString(CmccApiConstant.JSON_KEY_ICCID);
					if ( StringUtils.isNotBlank(activationTime) && StringUtils.isNotBlank(iccid)) {
						DeviceSimInfoActivationTimeDTO simInfoActivationTimeDTO = new DeviceSimInfoActivationTimeDTO();
						simInfoActivationTimeDTO.setActivationTime(activationTime);
						simInfoActivationTimeDTO.setIccid(iccid);
						simInfoActivationTimeDTO.setMsisdn(msisdn);
						list.add(simInfoActivationTimeDTO);
					}
				}
				// 保存激活时间到数据库
				if (CollectionUtils.isNotEmpty(list)) {
					deviceSimInfoService.updateDeviceSimInfoActivationTimeBatch(list);
//					for (DeviceSimInfoActivationTimeDTO dto : list) {
//						deviceSimInfoService.updateDeviceSimInfoActivationTime(dto);
//					}
				}
			}
		}
	}
}
